<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Sites;
use App\Models\Word;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class SitesController extends Controller
{
    //
    protected $categories;

    public function __construct()
    {
        $this->sites = Sites::orderBy('id', 'asc')->get();
        $this->categorys = Category::get();
    }

    public function index()
    {
//        $words=Word::get(['id','word'])->toArray();
//        foreach($words as $word){
//            dump($word);
//        }
//        die;
        //站点
        $sites = $this->sites;
        //分类
        $cates = $this->categorys;
        return view('sites.index', compact('sites', 'cates'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:60',
            'url' => 'required|max:60',
//            'watermark' => 'required',
        ]);
        $input = $request->input();
        //检测到水印图片，从temp文件夹中移出
        if (array_key_exists('watermark', $input)) {
            $old_path = $input['watermark'];
            $filename = explode('/', $input['watermark']);
            $input['watermark'] = $new_path = config('app.common.save_path') . end($filename);
            @copy('.' . $old_path, '.' . $new_path);
            @unlink('.' . $old_path);
        }
        //检测到category_id，取出
        if (array_key_exists('category_id', $input)) {
            $categorys = $input['category_id'];
            unset($input['category_id']);
        }
        DB::beginTransaction();
        try {
            $result = Sites::create($input);
            if ($result) {
                if (isset($categorys)) {
                    //同步中间表
                    $result->categorys()->sync($categorys, false);
                }
                DB::commit();
                session()->flash('success', '添加成功');
                return redirect()->route('sites.index');
            }
            DB::rollBack();
            session()->flash('error', '添加失败');
        } catch (\Exception $e) {
            session()->flash('error', '添加失败');
            DB::rollBack();
        }
        return redirect()->route('sites.index');
    }

    public function update(Request $request, $id)
    {
//        dump($request->input());
//        die;
        $this->validate($request, [
            'name' => 'required|max:60',
            'url' => 'required|max:60',
//            'watermark' => 'required',
        ]);
        //获取站点信息
        $site = Sites::find($id);
        //获取传值
        $input = $request->input();
        //检测到水印图片，从temp文件夹中移出
        if (array_key_exists('watermark', $input)) {
            if ($input['watermark'] != $site['watermark']) {
                $old_path = $input['watermark'];
                $filename = explode('/', $input['watermark']);
                $input['watermark'] = $new_path = config('app.common.save_path') . end($filename);
                @copy('.' . $old_path, '.' . $new_path);
                @unlink('.' . $old_path);   //删除缓存图片
                @unlink('.' . $site['watermark']);  //删除旧图片
            }
        }
        //检测到category_id，取出
        if (array_key_exists('category_id', $input)) {
            $categorys = $input['category_id'];
            unset($input['category_id']);
        }
        DB::beginTransaction();
        try {
            //更新数据
            $result = $site->update($input);
            if ($result) {
                if (isset($categorys)) {
                    //同步中间表
                    $site->categorys()->sync($categorys);
                }
                DB::commit();
                session()->flash('success', '修改成功');
            }
            session()->flash('error', '修改失败');
            DB::rollBack();
        } catch (\Exception $e) {
            session()->flash('error', '修改成功');
            DB::rollBack();
        }
        return redirect()->route('sites.index');
    }

    public function destroy($id)
    {
        $category = Sites::findOrFail($id);
        $res2 = $category->delete();
        if ($res2)
            session()->flash('success', '删除成功');
        else
            session()->flash('error', '删除失败');
        return redirect()->route('sites.index');
    }
}
